package com.fyales.android.api.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.TreeMap;

/**
 * @author fyales
 * @since 15/12/29.
 */
public class SignUtil {
    /**
     * 签名方法
     *
     * ref：
     * http://wiki.corp.vipshop.com/pages/viewpage.action?pageId=26644017
     */
    public static String makeSign(TreeMap<String, String> params, String secretKey, String charset ) {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        byte[] array = null;
        try {
            String userSecret = null;
            if(userSecret != null && userSecret.length() > 0){
                byteStream.write((secretKey + "&" + userSecret).getBytes(charset));
            }
            else {
                byteStream.write(secretKey.getBytes(charset));
            }

            for ( String key : params.keySet() ) {
                byteStream.write( params.get( key ).getBytes(charset) );
            }

            array = byteStream.toByteArray();
            byteStream.close();
        } catch ( UnsupportedEncodingException e ) {
            e.printStackTrace();
        } catch ( IOException e ) {
            e.printStackTrace();
        }
        String sign = EnctryptUtils.makeMd5Sum(array);
        return sign;
    }
}
